'use strict';
//首页
const Controller = require('egg').Controller;

class IndexController extends Controller {
  //首页 
  async index() {
    const { ctx, app } = this
    let newtime = new Date(), Op = app.Sequelize.Op;
    //轮播图
    let banner = await app.model.Banner.findAndCountAll({
      where: {
        statr_time: {
          [Op.lte]: '%' + newtime + '%'
        },
        end_time: {
          [Op.gte]: '%' + newtime + '%'
        }
      }
    })
    //分类
    let classlist = await app.model.Class.findAndCountAll({
      where: {
        status: '1'
      }
    })
    ctx.apiSuccess({ banner, classlist })
  }
  //首页 门店 
  async indexshop() {
    const { ctx, app } = this
    let { page, limit, latitude, longitude, popularity, is_recommend, title } = ctx.request.body
    page = page ? parseInt(page) : 1;
    limit = limit ? parseInt(limit) : 10;
    let offset = (page - 1) * limit;

    // 经纬度 最值
    const { minlng, maxlng, minlat, maxlat } = this.getMaxMinLongitudeLatitude(longitude, latitude, 20)
    // ctx.apiSuccess({minlng, maxlng, minlat, maxlat})
    // return
    let Op = app.Sequelize.Op;
    let where = {}, order = []
    if (popularity == 1) {//人气
      where = {}
      order = [['popularity', 'DESC'],]
    }
    if (is_recommend == 1) {//是否推荐
      where.is_recommend = '1'

    }
    if (title != '' && title != undefined) {
      where.title = {
        [Op.like]: '%' + title + '%'
      }
    }
    where.log = {
      [Op.between]: [minlng, maxlng]
    }
    where.lat = {
      [Op.between]: [minlat, maxlat]
    }
    where.status = '1'
    // console.log(where)

    let list = await app.model.Shop.findAndCountAll({
      where,
      order,
      offset,
      limit,
      include: [{
        model: app.model.Coupons,
        where: {
          status: '1'
        },
        order: [
          ['sort', 'DESC']
        ],
        attributes: ['title']
      }]
    })
    list.rows = list.rows.map(item => {
      let distance = 0
      if (list.rows.length && latitude && longitude) {
        distance = this.getDistance(item.lat, item.log, latitude, longitude) // 计算 距离
      }
      return {
        id: item.id,
        title: item.title,
        coupons_title: item.coupons[0].title,
        logo: item.logo,
        popularity: item.popularity,
        address: item.address,
        address_detaill: item.address_detaill,
        distance,
        is_recommend: item.is_recommend
      }
    })
    ctx.apiSuccess({ list, page, limit })
  }
  //分类 
  async classlist() {
    const { ctx, app } = this
    const { class_id, city_id } = ctx.query
    let where = {}
    if (class_id != '' && class_id != undefined) {
      where.class_id = class_id
    }
    if (city_id != '' && city_id != undefined) {
      where.city_id = city_id
    }
    where.status = '1'
    let list = await ctx.page(app.model.Shop, { ...where }, {
      attributes: ['id', 'title', 'logo', 'popularity', 'class_id', 'city_id', 'address'],
      include: [{
        model: app.model.Coupons,
        where: {
          status: '1'
        },
        order: [
          ['sort', 'DESC']
        ],
        attributes: ['title']
      }]
    })
    ctx.apiSuccess(list)
  }
  //门店 详情
  async delatil() {
    const { ctx, app } = this
    const id = ctx.request.body.id
    let listOne = await app.model.Shop.findOne({
      where: {
        id,
        status: '1'
      }
    })
    if (!listOne) {
      ctx.throw(400, '门店不存在或者禁用了')
    }
    let newTime = new Date(), Op = app.Sequelize.Op
    let couponslist = await app.model.Coupons.findAll({
      where: {
        shop_id: listOne.id,
        end_time: {
          [Op.gte]: newTime
        }
      },
      attributes:['id','title','pay_price','market_price','surplus_number','statr_time','end_time','agent_purchase','agent_price','agent_number']
    })
    ctx.apiSuccess({ listOne, couponslist })
  }
  



  // 根据 经纬度计算 一定千米的经纬度
  getMaxMinLongitudeLatitude(longitude, latitude, distince) {
    // console.log("MaxMinLongitudeLatitude", longitude, latitude);
    let r = 6371.393;    // 地球半径千米
    let lng = parseFloat(longitude);
    let lat = parseFloat(latitude);
    let dlng = 2 * Math.asin(Math.sin(distince / (2 * r)) / Math.cos(lat * Math.PI / 180));
    dlng = parseFloat(dlng * 180 / Math.PI);// 角度转为弧度
    let dlat = distince / r;
    dlat = parseFloat(dlat * 180 / Math.PI);
    // console.log(dlat, dlng)
    let minlat = lat - dlat;
    let maxlat = lat + dlat;
    let minlng = lng - dlng;
    let maxlng = lng + dlng;
    return {
      minlng, maxlng, minlat, maxlat
    }
  }
  //根据两点位置的经纬度获取距离
  getDistance(lat1, lng1, lat2, lng2) {
    let radLat1 = this.rad(lat1);
    let radLat2 = this.rad(lat2);
    let a = radLat1 - radLat2;

    let b = this.rad(lng1) - this.rad(lng2);
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; //输出为公里

    let distance = s;
    // 计算  km 与 m
    let distance_str = "";

    if (parseInt(distance) >= 1) {
      distance_str = distance.toFixed(1) + "km";
    } else {
      distance_str = distance * 1000 + "m";
    }

    //s=s.toFixed(4);

    // console.info('lyj 距离是', s);
    // console.info('lyj 距离是', distance_str);
    return distance_str;
  }
  // 经纬度转换成三角函数中度分表形式。
  rad(d) {
    return d * Math.PI / 180.0;
  }
}

module.exports = IndexController;
